package com.example.orderservice.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.DefaultJackson2JavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {


    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, Jackson2JsonMessageConverter jackson2JsonMessageConverter) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter);
        return rabbitTemplate;
    }
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();

        // 1. 创建类型映射器
        DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper();
        // 2. 配置“生产者类 → 消费者类”的映射关系
        Map<String, Class<?>> classMappings = new HashMap<>();
        // 键：生产者消息头__TypeId__中的类路径（必须与生产者一致）
        // 值：消费者自己的实体类（UserDTO）
        classMappings.put(
                "com.example.logisticsservice.model.UserInfo",
                com.example.orderservice.model.UserInfo.class
        );
        typeMapper.setIdClassMapping(classMappings);

        // 3. 将类型映射器绑定到转换器
        converter.setJavaTypeMapper(typeMapper);
        return converter;
    }

}
